package com.mygame.game_server;



import java.util.Iterator;
import java.util.Stack;

public class test {

    public static void main(String[] args) {
        int[] s = {4,2,3};
        System.err.println(trap(s));
    }
    public static int trap(int[] height) {
        int maxIndex = -1;
        int res = 0;
        Stack<Integer> stack = new Stack<Integer>();
        for (int i = 0; i < height.length; i++) {
            if (i == 0) {
                maxIndex = i;
                continue;
            }
            if (height[i] >= height[maxIndex]) {
                Iterator<Integer> j = stack.iterator();
                while (j.hasNext()) {
                    res += height[maxIndex] - j.next();
                }
                stack.clear();
                maxIndex = i;
            } else if (i == height.length - 1) {
                stack.clear();
                int maxIndex1 = -1;
                for (int j = i; j >= maxIndex; j--) {
                    if (maxIndex1 == -1){
                        maxIndex1 = j;
                        continue;
                    }
                    if (height[j] >= height[maxIndex1]) {
                        Iterator<Integer> t = stack.iterator();
                        while (t.hasNext()) {
                            res += height[maxIndex1] - t.next();
                        }
                        maxIndex1 = j;
                        stack.clear();
                    } else {
                        stack.push(height[j]);
                    }

                }
            } else {
                stack.push(height[i]);
            }
        }
        return res;
    }
}
